import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'mood.dart';
import 'package:flutter/foundation.dart';
import 'psychological_test.dart';
import 'thought_record.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._init();
  static Database? _database;
  static SharedPreferences? _prefs;

  DatabaseHelper._init();

  static const String _testRecordsTable = 'test_records';

  Future<dynamic> get database async {
    if (kIsWeb) {
      if (_prefs != null) return _prefs!;
      _prefs = await SharedPreferences.getInstance();
      await _initWebStorage(); // 确保Web存储被初始化
      return _prefs!;
    } else {
      if (_database != null) return _database!;
      _database = await _initDB('mood_diary.db');
      return _database!;
    }
  }

  Future<Database> _initDB(String filePath) async {
    if (kIsWeb) throw UnsupportedError('SQLite is not supported on Web platform');
    
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(
      path,
      version: 7,
      onCreate: _createDB,
      onUpgrade: _onUpgrade,
    );
  }

  // Web平台的数据初始化
  Future<void> _initWebStorage() async {
    final prefs = await SharedPreferences.getInstance();
    debugPrint('Checking web storage initialization...');
    debugPrint('initialized: ${prefs.containsKey('initialized')}');
    
    // 强制重新初始化数据
    await prefs.remove('initialized');
    await prefs.remove('emotion_triggers');
    await prefs.remove('body_reactions');
    
    if (!prefs.containsKey('initialized')) {
      debugPrint('Initializing web storage with default data');
      // 初始化Web存储的默认数据
      await prefs.setString('moods', json.encode([]));
      await prefs.setString('thoughts', json.encode([]));
      await prefs.setString('test_records', json.encode([]));
      
      // 初始化情绪触发器和身体反应数据
      final defaultTriggers = _getDefaultEmotionTriggers();
      final defaultReactions = _getDefaultBodyReactions();
      
      debugPrint('Setting default triggers: ${defaultTriggers.length} items');
      debugPrint('Setting default reactions: ${defaultReactions.length} items');
      
      await prefs.setString('emotion_triggers', json.encode(defaultTriggers));
      await prefs.setString('body_reactions', json.encode(defaultReactions));
      await prefs.setBool('initialized', true);
      
      // 验证数据是否正确保存
      final savedTriggers = prefs.getString('emotion_triggers');
      final savedReactions = prefs.getString('body_reactions');
      debugPrint('Saved triggers: $savedTriggers');
      debugPrint('Saved reactions: $savedReactions');
    }
  }

  List<Map<String, dynamic>> _getDefaultEmotionTriggers() {
    return [
      {
        'category_name': '现实压力源',
        'triggers': '工作压力,学业压力,经济压力,时间压力,生活琐事,环境变化,健康问题',
        'mood_range': 'negative'
      },
      {
        'category_name': '关系冲突类',
        'triggers': '人际矛盾,沟通不畅,期望落空,被忽视,被误解,被批评,关系疏离',
        'mood_range': 'negative'
      },
      {
        'category_name': '自我认知失调',
        'triggers': '自我否定,能力怀疑,价值质疑,目标迷茫,完美主义,比较心理,自责内疚',
        'mood_range': 'negative'
      },
      {
        'category_name': '环境应激源',
        'triggers': '噪音干扰,天气变化,空间拥挤,时间紧迫,信息过载,环境不适,突发事件',
        'mood_range': 'negative'
      },
      {
        'category_name': '生理诱发因素',
        'triggers': '睡眠不足,饮食不当,身体不适,疲劳过度,生理周期,天气影响,环境变化',
        'mood_range': 'negative'
      },
      {
        'category_name': '社交与人际关系',
        'triggers': '与伴侣的浪漫时刻,家人团聚或视频通话,朋友聚会/深度聊天,收到他人赞美或感谢,帮助他人解决问题,结识新朋友/有趣的对话,参加团体活动,被社群认可或接纳,感受到他人的关心',
        'mood_range': 'positive'
      },
      {
        'category_name': '成就与目标',
        'triggers': '学会新技能,突破自我设定的挑战,完成长期坚持的习惯,项目获得成功或认可,考试/考核成绩优异,达成年度/季度关键目标,完成当日待办清单,解决一个棘手问题,收到客户/老师积极反馈',
        'mood_range': 'positive'
      },
      {
        'category_name': '体验与享受',
        'triggers': '品尝美食/喜爱的饮品,听到喜欢的音乐/播客,闻到花香/雨后空气,观看电影/演出/展览,玩游戏通关或创造作品,阅读书籍/诗歌产生共鸣,户外徒步/露营体验,观察星空/日出日落,与宠物互动',
        'mood_range': 'positive'
      },
      {
        'category_name': '自我实现与意义感',
        'triggers': '参与公益活动/捐赠,坚持环保行为,为他人提供情感支持,完成绘画/写作/手作,即兴创作（烹饪、园艺等）,分享原创内容获得共鸣,冥想/正念练习后的平静,哲学/宗教带来的顿悟,对人生有新的积极认知',
        'mood_range': 'positive'
      },
      {
        'category_name': '健康与身体状态',
        'triggers': '获得优质睡眠后焕发活力,运动后内啡肽释放的快感,病痛缓解/体检指标好转,完成心理咨询后的释然,成功化解负面情绪,接纳自我后的轻松感',
        'mood_range': 'positive'
      },
      {
        'category_name': '物质与环境',
        'triggers': '收到期待已久的礼物,购买到心仪物品,经济压力缓解（加薪、理财收益）,布置温馨的居住空间,天气晴好带来的愉悦,进入整洁有序的环境',
        'mood_range': 'positive'
      },
      {
        'category_name': '意外之喜',
        'triggers': '偶遇美好事物,随机善意,中奖/抽奖获得惊喜',
        'mood_range': 'positive'
      },
      {
        'category_name': '日常事务完成',
        'triggers': '准时完成工作/学习任务,整理房间/收拾物品,完成健身/散步等规律活动',
        'mood_range': 'neutral'
      },
      {
        'category_name': '环境舒适状态',
        'triggers': '处于安静/整洁的空间,天气温和（如阴天/微风）,重复性低难度活动（如泡茶、浇花）',
        'mood_range': 'neutral'
      },
      {
        'category_name': '心理调节行为',
        'triggers': '正念呼吸/短暂闭目养神后,理性接纳暂时无法解决的事,阶段性目标达成（如存钱进度过半）',
        'mood_range': 'neutral'
      }
    ];
  }

  List<Map<String, dynamic>> _getDefaultBodyReactions() {
    return [
      {
        'category_name': '头部反应',
        'reactions': '头皮发麻,额头冒冷汗,耳鸣/耳闷,视力模糊/眼压升高,头痛,头晕,偏头痛,太阳穴紧绷',
        'mood_range': 'negative'
      },
      {
        'category_name': '睡眠反应',
        'reactions': '睡眠惊跳,睡眠呼吸暂停感,睡眠瘫痪,昼夜节律紊乱,失眠,多梦,早醒,嗜睡',
        'mood_range': 'negative'
      },
      {
        'category_name': '消化反应',
        'reactions': '胃胀气/打嗝频繁,肠鸣音亢进,反酸烧心,便秘,胃痛,食欲变化,恶心,腹泻',
        'mood_range': 'negative'
      },
      {
        'category_name': '其他反应',
        'reactions': '心慌心悸,手汗增多/掌心潮湿,尿频尿急,皮肤瘙痒/荨麻疹,体温异常,胸闷,手抖,肌肉酸痛,疲劳感',
        'mood_range': 'negative'
      },
      {
        'category_name': '面部与表情',
        'reactions': '自然微笑,眼睛发亮/瞳孔放大,脸色红润',
        'mood_range': 'positive'
      },
      {
        'category_name': '呼吸与心跳',
        'reactions': '呼吸变深/节奏舒缓,心跳加快/有力,叹息式呼气',
        'mood_range': 'positive'
      },
      {
        'category_name': '肌肉与体态',
        'reactions': '肌肉放松,身体舒展/挺直,跳跃/手舞足蹈',
        'mood_range': 'positive'
      },
      {
        'category_name': '体温与触觉',
        'reactions': '身体温暖感,皮肤敏感度提升,手心微汗',
        'mood_range': 'positive'
      },
      {
        'category_name': '消化与代谢反应',
        'reactions': '饥饿感提升,肠胃放松',
        'mood_range': 'positive'
      },
      {
        'category_name': '能量水平感知',
        'reactions': '精力充沛/活力感,身体轻盈感',
        'mood_range': 'positive'
      },
      {
        'category_name': '神经系统',
        'reactions': '轻微颤抖,头皮发麻/震颤',
        'mood_range': 'positive'
      },
      {
        'category_name': '呼吸与循环',
        'reactions': '呼吸平稳均匀（无急促/憋气感）,心跳节奏稳定（无突然加速/漏拍）',
        'mood_range': 'neutral'
      },
      {
        'category_name': '肌肉与体感',
        'reactions': '肩颈放松无紧绷,手脚自然舒展（非握拳/蜷缩）,体温不冷不热（无明显燥热/发冷）',
        'mood_range': 'neutral'
      },
      {
        'category_name': '感官与能量',
        'reactions': '眼神自然不飘忽（非涣散或紧盯）,皮肤触感正常（无发麻/刺痛）,身体无明显沉重或轻飘感',
        'mood_range': 'neutral'
      }
    ];
  }

  // 修改插入方法以支持Web平台
  Future<int?> insertMood(Mood mood) async {
    try {
      if (kIsWeb) {
        final prefs = await database as SharedPreferences;
        final moods = json.decode(prefs.getString('moods') ?? '[]') as List;
        final map = mood.toMap();
        map['id'] = DateTime.now().millisecondsSinceEpoch;
        
        // 确保 createdAt 是当前时间的 ISO 字符串格式
        if (map['createdAt'] == null) {
          map['createdAt'] = DateTime.now().toIso8601String();
        }
        
        moods.add(map);
        await prefs.setString('moods', json.encode(moods));
        return map['id'] as int;
      } else {
        final db = await database as Database;
        final map = mood.toMap();
        map.remove('id');
        return await db.insert('moods', map);
      }
    } catch (e) {
      debugPrint('插入情绪记录失败: $e');
      return null;
    }
  }

  // 修改查询方法以支持Web平台
  Future<List<Mood>> getMoods() async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final moodsStr = prefs.getString('moods') ?? '[]';
      final moodsList = json.decode(moodsStr) as List;
      final moods = moodsList.map((map) => Mood.fromMap(Map<String, dynamic>.from(map))).toList();
      
      // 按创建时间倒序排序，确保最新的记录在最前面
      moods.sort((a, b) => b.createdAt.compareTo(a.createdAt));
      
      return moods;
    } else {
      final db = await database as Database;
      final List<Map<String, dynamic>> maps = await db.query('moods', orderBy: 'createdAt DESC');
      return List.generate(maps.length, (i) => Mood.fromMap(maps[i]));
    }
  }

  // 修改测试记录相关方法以支持Web平台
  Future<int> insertTestRecord(TestRecord record) async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final records = json.decode(prefs.getString('test_records') ?? '[]') as List;
      final map = record.toMap();
      map['id'] = DateTime.now().millisecondsSinceEpoch;
      records.add(map);
      await prefs.setString('test_records', json.encode(records));
      return map['id'] as int;
    } else {
      final db = await database as Database;
      return await db.insert(_testRecordsTable, record.toMap());
    }
  }

  Future<List<TestRecord>> getAllTestRecords() async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final recordsStr = prefs.getString('test_records') ?? '[]';
      final recordsList = json.decode(recordsStr) as List;
      return recordsList.map((map) => TestRecord.fromMap(Map<String, dynamic>.from(map))).toList();
    } else {
      final db = await database as Database;
      final List<Map<String, dynamic>> maps = await db.query(
        'test_records',
        orderBy: 'test_date DESC',
      );
      return List.generate(maps.length, (i) => TestRecord.fromMap(maps[i]));
    }
  }

  Future<void> _createDB(Database db, int version) async {
    try {
      // 创建情绪记录表
      await db.execute('''
        CREATE TABLE moods (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          moodType INTEGER NOT NULL,
          intensity INTEGER NOT NULL,
          emotions TEXT NOT NULL,
          triggers TEXT NOT NULL,
          bodyReactions TEXT NOT NULL,
          description TEXT NOT NULL,
          imagePath TEXT,
          createdAt TEXT NOT NULL,
          date TEXT NOT NULL
        )
      ''');

      // 创建想法记录表
      await db.execute('''
        CREATE TABLE thoughts (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          thought TEXT NOT NULL,
          distortion_labels TEXT NOT NULL,
          emotional_intensity INTEGER NOT NULL,
          timestamp TEXT NOT NULL,
          balanced_view TEXT,
          action_plan TEXT,
          reflection_answers TEXT,
          positive_thought TEXT
        )
      ''');

      // 创建情绪触发因素表
      await db.execute('''
        CREATE TABLE emotion_triggers (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          category_name TEXT NOT NULL,
          triggers TEXT NOT NULL,
          mood_range TEXT NOT NULL
        )
      ''');

      // 创建身体反应表
      await db.execute('''
        CREATE TABLE body_reactions (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          category_name TEXT NOT NULL,
          reactions TEXT NOT NULL,
          mood_range TEXT NOT NULL
        )
      ''');

      // 创建心理测试记录表
      await db.execute('''
        CREATE TABLE $_testRecordsTable (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          test_type INTEGER NOT NULL,
          test_date TEXT NOT NULL,
          answers TEXT NOT NULL,
          raw_score REAL NOT NULL,
          standard_score REAL NOT NULL,
          conclusion TEXT NOT NULL,
          suggestion TEXT NOT NULL
        )
      ''');

      // 插入初始数据
      await _insertInitialData(db);
    } catch (e) {
      debugPrint('创建数据库表失败: $e');
      rethrow;
    }
  }

  Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
    if (oldVersion < 2) {
      // 添加 emotions 和 date 列
      await db.execute('ALTER TABLE moods ADD COLUMN emotions TEXT NOT NULL DEFAULT ""');
      await db.execute('ALTER TABLE moods ADD COLUMN date TEXT NOT NULL DEFAULT ""');
    }
    
    if (oldVersion < 3) {
      // 删除旧的身体反应数据
      await db.delete('body_reactions', where: 'mood_range = ?', whereArgs: ['negative']);
      
      // 插入新的身体反应数据
      await db.insert('body_reactions', {
        'category_name': '头部反应',
        'reactions': '头皮发麻,额头冒冷汗,耳鸣/耳闷,视力模糊/眼压升高,头痛,头晕,偏头痛,太阳穴紧绷',
        'mood_range': 'negative'
      });
      await db.insert('body_reactions', {
        'category_name': '睡眠反应',
        'reactions': '睡眠惊跳,睡眠呼吸暂停感,睡眠瘫痪,昼夜节律紊乱,失眠,多梦,早醒,嗜睡',
        'mood_range': 'negative'
      });
      await db.insert('body_reactions', {
        'category_name': '消化反应',
        'reactions': '胃胀气/打嗝频繁,肠鸣音亢进,反酸烧心,便秘,胃痛,食欲变化,恶心,腹泻',
        'mood_range': 'negative'
      });
      await db.insert('body_reactions', {
        'category_name': '其他反应',
        'reactions': '心慌心悸,手汗增多/掌心潮湿,尿频尿急,皮肤瘙痒/荨麻疹,体温异常,胸闷,手抖,肌肉酸痛,疲劳感',
        'mood_range': 'negative'
      });
    }

    if (oldVersion < 4) {
      // 删除旧的身体反应数据
      await db.delete('body_reactions', where: 'mood_range = ?', whereArgs: ['negative']);
      
      // 插入合并后的身体反应数据
      await db.insert('body_reactions', {
        'category_name': '头部反应',
        'reactions': '头皮发麻,额头冒冷汗,耳鸣/耳闷,视力模糊/眼压升高,头痛,头晕,偏头痛,太阳穴紧绷',
        'mood_range': 'negative'
      });
      await db.insert('body_reactions', {
        'category_name': '睡眠反应',
        'reactions': '睡眠惊跳,睡眠呼吸暂停感,睡眠瘫痪,昼夜节律紊乱,失眠,多梦,早醒,嗜睡',
        'mood_range': 'negative'
      });
      await db.insert('body_reactions', {
        'category_name': '消化反应',
        'reactions': '胃胀气/打嗝频繁,肠鸣音亢进,反酸烧心,便秘,胃痛,食欲变化,恶心,腹泻',
        'mood_range': 'negative'
      });
      await db.insert('body_reactions', {
        'category_name': '其他反应',
        'reactions': '心慌心悸,手汗增多/掌心潮湿,尿频尿急,皮肤瘙痒/荨麻疹,体温异常,胸闷,手抖,肌肉酸痛,疲劳感',
        'mood_range': 'negative'
      });
    }

    if (oldVersion < 5) {
      // 删除旧的测试记录表（如果存在）
      await db.execute('DROP TABLE IF EXISTS $_testRecordsTable');
      
      // 重新创建测试记录表
      await db.execute('''
        CREATE TABLE $_testRecordsTable (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          test_type INTEGER NOT NULL,
          test_date TEXT NOT NULL,
          answers TEXT NOT NULL,
          raw_score REAL NOT NULL,
          standard_score REAL NOT NULL,
          conclusion TEXT NOT NULL,
          suggestion TEXT NOT NULL
        )
      ''');
    }

    if (oldVersion < 6) {
      // 创建想法记录表
      await db.execute('''
        CREATE TABLE thoughts (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          thought TEXT NOT NULL,
          distortion_labels TEXT NOT NULL,
          emotional_intensity INTEGER NOT NULL,
          timestamp TEXT NOT NULL,
          balanced_view TEXT,
          action_plan TEXT,
          reflection_answers TEXT,
          positive_thought TEXT
        )
      ''');
    }

    if (oldVersion < 7) {
      // 为 thoughts 表添加 positive_thought 列
      await db.execute('ALTER TABLE thoughts ADD COLUMN positive_thought TEXT');
    }
  }

  Future<void> _insertInitialData(Database db) async {
    // 插入情绪诱因数据
    await db.insert('emotion_triggers', {
      'category_name': '现实压力源',
      'triggers': '工作压力,学业压力,经济压力,时间压力,生活琐事,环境变化,健康问题',
      'mood_range': 'negative'
    });
    await db.insert('emotion_triggers', {
      'category_name': '关系冲突类',
      'triggers': '人际矛盾,沟通不畅,期望落空,被忽视,被误解,被批评,关系疏离',
      'mood_range': 'negative'
    });
    await db.insert('emotion_triggers', {
      'category_name': '自我认知失调',
      'triggers': '自我否定,能力怀疑,价值质疑,目标迷茫,完美主义,比较心理,自责内疚',
      'mood_range': 'negative'
    });
    await db.insert('emotion_triggers', {
      'category_name': '环境应激源',
      'triggers': '噪音干扰,天气变化,空间拥挤,时间紧迫,信息过载,环境不适,突发事件',
      'mood_range': 'negative'
    });
    await db.insert('emotion_triggers', {
      'category_name': '生理诱发因素',
      'triggers': '睡眠不足,饮食不当,身体不适,疲劳过度,生理周期,天气影响,环境变化',
      'mood_range': 'negative'
    });

    // 插入负面情绪身体反应数据
    await db.insert('body_reactions', {
      'category_name': '头部反应',
      'reactions': '头皮发麻,额头冒冷汗,耳鸣/耳闷,视力模糊/眼压升高,头痛,头晕,偏头痛,太阳穴紧绷',
      'mood_range': 'negative'
    });
    await db.insert('body_reactions', {
      'category_name': '睡眠反应',
      'reactions': '睡眠惊跳,睡眠呼吸暂停感,睡眠瘫痪,昼夜节律紊乱,失眠,多梦,早醒,嗜睡',
      'mood_range': 'negative'
    });
    await db.insert('body_reactions', {
      'category_name': '消化反应',
      'reactions': '胃胀气/打嗝频繁,肠鸣音亢进,反酸烧心,便秘,胃痛,食欲变化,恶心,腹泻',
      'mood_range': 'negative'
    });
    await db.insert('body_reactions', {
      'category_name': '其他反应',
      'reactions': '心慌心悸,手汗增多/掌心潮湿,尿频尿急,皮肤瘙痒/荨麻疹,体温异常,胸闷,手抖,肌肉酸痛,疲劳感',
      'mood_range': 'negative'
    });

    // 插入情绪触发器数据
    final triggerData = [
      // 正面情绪诱因
      {
        'category_name': '社交与人际关系',
        'triggers': '与伴侣的浪漫时刻,家人团聚或视频通话,朋友聚会/深度聊天,收到他人赞美或感谢,帮助他人解决问题,结识新朋友/有趣的对话,参加团体活动,被社群认可或接纳,感受到他人的关心',
        'mood_range': 'positive'
      },
      {
        'category_name': '成就与目标',
        'triggers': '学会新技能,突破自我设定的挑战,完成长期坚持的习惯,项目获得成功或认可,考试/考核成绩优异,达成年度/季度关键目标,完成当日待办清单,解决一个棘手问题,收到客户/老师积极反馈',
        'mood_range': 'positive'
      },
      {
        'category_name': '体验与享受',
        'triggers': '品尝美食/喜爱的饮品,听到喜欢的音乐/播客,闻到花香/雨后空气,观看电影/演出/展览,玩游戏通关或创造作品,阅读书籍/诗歌产生共鸣,户外徒步/露营体验,观察星空/日出日落,与宠物互动',
        'mood_range': 'positive'
      },
      {
        'category_name': '自我实现与意义感',
        'triggers': '参与公益活动/捐赠,坚持环保行为,为他人提供情感支持,完成绘画/写作/手作,即兴创作（烹饪、园艺等）,分享原创内容获得共鸣,冥想/正念练习后的平静,哲学/宗教带来的顿悟,对人生有新的积极认知',
        'mood_range': 'positive'
      },
      {
        'category_name': '健康与身体状态',
        'triggers': '获得优质睡眠后焕发活力,运动后内啡肽释放的快感,病痛缓解/体检指标好转,完成心理咨询后的释然,成功化解负面情绪,接纳自我后的轻松感',
        'mood_range': 'positive'
      },
      {
        'category_name': '物质与环境',
        'triggers': '收到期待已久的礼物,购买到心仪物品,经济压力缓解（加薪、理财收益）,布置温馨的居住空间,天气晴好带来的愉悦,进入整洁有序的环境',
        'mood_range': 'positive'
      },
      {
        'category_name': '意外之喜',
        'triggers': '偶遇美好事物,随机善意,中奖/抽奖获得惊喜',
        'mood_range': 'positive'
      },
      // 平静情绪诱因
      {
        'category_name': '日常事务完成',
        'triggers': '准时完成工作/学习任务,整理房间/收拾物品,完成健身/散步等规律活动',
        'mood_range': 'neutral'
      },
      {
        'category_name': '环境舒适状态',
        'triggers': '处于安静/整洁的空间,天气温和（如阴天/微风）,重复性低难度活动（如泡茶、浇花）',
        'mood_range': 'neutral'
      },
      {
        'category_name': '心理调节行为',
        'triggers': '正念呼吸/短暂闭目养神后,理性接纳暂时无法解决的事,阶段性目标达成（如存钱进度过半）',
        'mood_range': 'neutral'
      },
    ];

    for (var data in triggerData) {
      await db.insert('emotion_triggers', data);
    }

    // 插入身体反应数据
    final reactionData = [
      // 正面情绪身体反应
      {
        'category_name': '面部与表情',
        'reactions': '自然微笑,眼睛发亮/瞳孔放大,脸色红润',
        'mood_range': 'positive'
      },
      {
        'category_name': '呼吸与心跳',
        'reactions': '呼吸变深/节奏舒缓,心跳加快/有力,叹息式呼气',
        'mood_range': 'positive'
      },
      {
        'category_name': '肌肉与体态',
        'reactions': '肌肉放松,身体舒展/挺直,跳跃/手舞足蹈',
        'mood_range': 'positive'
      },
      {
        'category_name': '体温与触觉',
        'reactions': '身体温暖感,皮肤敏感度提升,手心微汗',
        'mood_range': 'positive'
      },
      {
        'category_name': '消化与代谢反应',
        'reactions': '饥饿感提升,肠胃放松',
        'mood_range': 'positive'
      },
      {
        'category_name': '能量水平感知',
        'reactions': '精力充沛/活力感,身体轻盈感',
        'mood_range': 'positive'
      },
      {
        'category_name': '神经系统',
        'reactions': '轻微颤抖,头皮发麻/震颤',
        'mood_range': 'positive'
      },
      // 平静情绪身体反应
      {
        'category_name': '呼吸与循环',
        'reactions': '呼吸平稳均匀（无急促/憋气感）,心跳节奏稳定（无突然加速/漏拍）',
        'mood_range': 'neutral'
      },
      {
        'category_name': '肌肉与体感',
        'reactions': '肩颈放松无紧绷,手脚自然舒展（非握拳/蜷缩）,体温不冷不热（无明显燥热/发冷）',
        'mood_range': 'neutral'
      },
      {
        'category_name': '感官与能量',
        'reactions': '眼神自然不飘忽（非涣散或紧盯）,皮肤触感正常（无发麻/刺痛）,身体无明显沉重或轻飘感',
        'mood_range': 'neutral'
      },
    ];

    for (var data in reactionData) {
      await db.insert('body_reactions', data);
    }
  }

  Future<List<Map<String, dynamic>>> getEmotionTriggers(String moodRange) async {
    debugPrint('Getting emotion triggers for mood range: $moodRange');
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      
      // 检查初始化状态，如果未初始化则强制重新初始化
      if (!prefs.containsKey('initialized') || !prefs.containsKey('emotion_triggers')) {
        debugPrint('Web storage not initialized, initializing now...');
        await _initWebStorage();
      }
      
      final triggersStr = prefs.getString('emotion_triggers') ?? '[]';
      debugPrint('Raw triggers data length: ${triggersStr.length}');
      
      List<dynamic> allTriggers;
      try {
        allTriggers = json.decode(triggersStr);
        debugPrint('Decoded triggers: ${allTriggers.length} items');
      } catch (e) {
        debugPrint('Error decoding triggers: $e');
        // 如果解析失败，重新初始化
        await _initWebStorage();
        final newTriggersStr = prefs.getString('emotion_triggers') ?? '[]';
        allTriggers = json.decode(newTriggersStr);
      }
      
      final filteredTriggers = allTriggers.where((trigger) => 
        trigger['mood_range'] == moodRange
      ).toList();
      
      debugPrint('Filtered triggers: ${filteredTriggers.length} items for $moodRange');
      
      return List<Map<String, dynamic>>.from(filteredTriggers);
    } else {
      final db = await database as Database;
      final List<Map<String, dynamic>> maps = await db.query(
        'emotion_triggers',
        where: 'mood_range = ?',
        whereArgs: [moodRange],
      );
      debugPrint('Found ${maps.length} emotion triggers');
      return maps;
    }
  }

  Future<List<Map<String, dynamic>>> getBodyReactions(String moodRange) async {
    debugPrint('Getting body reactions for mood range: $moodRange');
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      
      // 检查初始化状态，如果未初始化则强制重新初始化
      if (!prefs.containsKey('initialized') || !prefs.containsKey('body_reactions')) {
        debugPrint('Web storage not initialized, initializing now...');
        await _initWebStorage();
      }
      
      final reactionsStr = prefs.getString('body_reactions') ?? '[]';
      debugPrint('Raw reactions data length: ${reactionsStr.length}');
      
      List<dynamic> allReactions;
      try {
        allReactions = json.decode(reactionsStr);
        debugPrint('Decoded reactions: ${allReactions.length} items');
      } catch (e) {
        debugPrint('Error decoding reactions: $e');
        // 如果解析失败，重新初始化
        await _initWebStorage();
        final newReactionsStr = prefs.getString('body_reactions') ?? '[]';
        allReactions = json.decode(newReactionsStr);
      }
      
      final filteredReactions = allReactions.where((reaction) => 
        reaction['mood_range'] == moodRange
      ).toList();
      
      debugPrint('Filtered reactions: ${filteredReactions.length} items for $moodRange');
      
      return List<Map<String, dynamic>>.from(filteredReactions);
    } else {
      final db = await database as Database;
      final List<Map<String, dynamic>> maps = await db.query(
        'body_reactions',
        where: 'mood_range = ?',
        whereArgs: [moodRange],
      );
      debugPrint('Found ${maps.length} body reactions');
      return maps;
    }
  }

  Future<bool> deleteMood(int id) async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final moodsStr = prefs.getString('moods') ?? '[]';
      final List<dynamic> moods = json.decode(moodsStr);
      final newMoods = moods.where((m) => m['id'] != id).toList();
      await prefs.setString('moods', json.encode(newMoods));
      return true;
    } else {
      final db = await database as Database;
      final result = await db.delete(
        'moods',
        where: 'id = ?',
        whereArgs: [id],
      );
      return result > 0;
    }
  }

  Future<void> resetDatabase() async {
    try {
      if (kIsWeb) {
        final prefs = await database as SharedPreferences;
        await prefs.clear();
        await _initWebStorage();
      } else {
        final db = await database as Database;
        await db.execute('DROP TABLE IF EXISTS moods');
        await db.execute('DROP TABLE IF EXISTS emotion_triggers');
        await db.execute('DROP TABLE IF EXISTS body_reactions');
        await db.execute('DROP TABLE IF EXISTS $_testRecordsTable');
        await db.execute('DROP TABLE IF EXISTS thoughts');
        await _createDB(db, 7);
      }
    } catch (e) {
      debugPrint('重置数据库失败: $e');
      rethrow;
    }
  }

  // 获取所有测试记录
  Future<List<TestRecord>> getTestRecordsByType(TestType type) async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final recordsStr = prefs.getString('test_records') ?? '[]';
      final List<dynamic> allRecords = json.decode(recordsStr);
      final filteredRecords = allRecords.where((record) =>
        record['test_type'] == type.index
      ).toList();
      return filteredRecords.map((map) => TestRecord.fromMap(Map<String, dynamic>.from(map))).toList();
    } else {
      final db = await database as Database;
      final List<Map<String, dynamic>> maps = await db.query(
        _testRecordsTable,
        where: 'test_type = ?',
        whereArgs: [type.index],
      );
      return List.generate(maps.length, (i) => TestRecord.fromMap(maps[i]));
    }
  }

  // 删除测试记录
  Future<int> deleteTestRecord(int id) async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final recordsStr = prefs.getString('test_records') ?? '[]';
      final List<dynamic> records = json.decode(recordsStr);
      final newRecords = records.where((record) => record['id'] != id).toList();
      await prefs.setString('test_records', json.encode(newRecords));
      return 1;
    } else {
      final db = await database as Database;
      return await db.delete(
        _testRecordsTable,
        where: 'id = ?',
        whereArgs: [id],
      );
    }
  }

  // 插入示例SCL90测试记录
  Future<void> insertSampleSCL90Records() async {
    final db = await database;
    
    final scl90Records = [
      {
        'test_type': TestType.SCL90.index,
        'test_date': DateTime.now().subtract(const Duration(days: 30)).toIso8601String(),
        'answers': List.generate(90, (index) => 
          index < 30 ? 2 : (index < 60 ? 1 : 3)
        ),
        'raw_score': 180.0,
        'standard_score': 2.0,
        'conclusion': 'SCL-90量表测评显示存在一定的心理健康风险',
        'suggestion': '建议关注自己的心理健康状况，适当寻求专业帮助。可以尝试：\n1. 保持规律的作息和健康的生活方式\n2. 进行适度运动和放松训练\n3. 与亲友倾诉或寻求专业心理咨询',
      },
      {
        'test_type': TestType.SCL90.index,
        'test_date': DateTime.now().subtract(const Duration(days: 15)).toIso8601String(),
        'answers': List.generate(90, (index) => 
          index < 40 ? 1 : (index < 80 ? 2 : 1)
        ),
        'raw_score': 140.0,
        'standard_score': 1.56,
        'conclusion': 'SCL-90量表测评显示心理状态有所改善',
        'suggestion': '您的整体心理状态相对稳定，建议：\n1. 继续保持良好的生活习惯\n2. 培养积极的兴趣爱好\n3. 建立健康的人际关系网络',
      },
      {
        'test_type': TestType.SCL90.index,
        'test_date': DateTime.now().toIso8601String(),
        'answers': List.generate(90, (index) => 
          index < 50 ? 1 : (index < 85 ? 2 : 3)
        ),
        'raw_score': 160.0,
        'standard_score': 1.78,
        'conclusion': 'SCL-90量表测评显示心理状态基本稳定',
        'suggestion': '建议继续保持积极的心态，可以：\n1. 规律作息，保持充足睡眠\n2. 适度运动，放松身心\n3. 培养兴趣爱好，丰富生活内容',
      }
    ];

    for (var record in scl90Records) {
      try {
        await db.insert(_testRecordsTable, {
          ...record,
          'answers': (record['answers'] as List<int>).join(','),
        });
      } catch (e) {
        debugPrint('插入SCL90测试记录失败: $e');
      }
    }
  }

  Future<ThoughtRecord> insertThoughtRecord(ThoughtRecord record) async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final thoughts = json.decode(prefs.getString('thoughts') ?? '[]') as List;
      final recordMap = record.toMap();
      recordMap['id'] = DateTime.now().millisecondsSinceEpoch;
      thoughts.add(recordMap);
      await prefs.setString('thoughts', json.encode(thoughts));
      return record.copyWith(id: recordMap['id'] as int);
    } else {
      final db = await database as Database;
      debugPrint('准备插入想法记录: ${record.toString()}');
      debugPrint('想法内容: ${record.thought}');
      debugPrint('积极想法: ${record.positiveThought}');
      debugPrint('平衡观点: ${record.balancedView}');
      debugPrint('行动计划: ${record.actionPlan}');
      final recordMap = record.toMap();
      debugPrint('转换为Map后的数据: $recordMap');
      final id = await db.insert('thoughts', recordMap);
      debugPrint('插入成功，ID: $id');
      return record.copyWith(id: id);
    }
  }

  Future<List<ThoughtRecord>> getAllThoughtRecords() async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final thoughtsStr = prefs.getString('thoughts') ?? '[]';
      final thoughtsList = json.decode(thoughtsStr) as List;
      return thoughtsList
        .map((map) => ThoughtRecord.fromMap(Map<String, dynamic>.from(map)))
        .toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
    } else {
      final db = await database as Database;
      final List<Map<String, dynamic>> maps = await db.query(
        'thoughts',
        orderBy: 'timestamp DESC',
      );
      return List.generate(maps.length, (i) => ThoughtRecord.fromMap(maps[i]));
    }
  }

  Future<ThoughtRecord?> getThoughtRecord(int id) async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final thoughtsStr = prefs.getString('thoughts') ?? '[]';
      final List<dynamic> thoughts = json.decode(thoughtsStr);
      final thought = thoughts.firstWhere(
        (t) => t['id'] == id,
        orElse: () => null
      );
      return thought == null ? null : ThoughtRecord.fromMap(Map<String, dynamic>.from(thought));
    } else {
      final db = await database as Database;
      final List<Map<String, dynamic>> maps = await db.query(
        'thoughts',
        where: 'id = ?',
        whereArgs: [id],
      );
      if (maps.isEmpty) return null;
      return ThoughtRecord.fromMap(maps.first);
    }
  }

  Future<int> updateThoughtRecord(ThoughtRecord record) async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final thoughtsStr = prefs.getString('thoughts') ?? '[]';
      final List<dynamic> thoughts = json.decode(thoughtsStr);
      final index = thoughts.indexWhere((t) => t['id'] == record.id);
      if (index != -1) {
        thoughts[index] = record.toMap();
        await prefs.setString('thoughts', json.encode(thoughts));
        return 1;
      }
      return 0;
    } else {
      final db = await database as Database;
      return db.update(
        'thoughts',
        record.toMap(),
        where: 'id = ?',
        whereArgs: [record.id],
      );
    }
  }

  Future<int> deleteThoughtRecord(int id) async {
    if (kIsWeb) {
      final prefs = await database as SharedPreferences;
      final thoughtsStr = prefs.getString('thoughts') ?? '[]';
      final List<dynamic> thoughts = json.decode(thoughtsStr);
      final newThoughts = thoughts.where((t) => t['id'] != id).toList();
      await prefs.setString('thoughts', json.encode(newThoughts));
      return 1;
    } else {
      final db = await database as Database;
      return await db.delete(
        'thoughts',
        where: 'id = ?',
        whereArgs: [id],
      );
    }
  }

  Future<void> close() async {
    if (!kIsWeb) {
      final db = await database as Database;
      await db.close();
    }
  }
} 